<!--
 * @Description:
 * @Author: zhaolei
 * @Date: 2023-04-10 18:16:02
-->
<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      @on-load="getList"
      @search-reset="searchReset"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
    >
      <template #nickName="{ row }">
        <span>{{ row.nickName }}</span>
        <span v-if="row.formerName && row.nickName !== row.formerName">
          (曾用名：{{ row.formerName }})
        </span>
      </template>
      <!--品种-->
      <template #petTypeSearch="{ row }">
        <el-cascader
          v-model="row.petType"
          :options="options"
          :props="props"
          collapse-tags
          clearable
        ></el-cascader>
      </template>
      <template v-slot:code="{ row }">
        <el-button
          type="text"
          @click="view(row)"
        >
          {{ row.code }}
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button
          style="margin-right: 20px"
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="add"
        >
          添加
        </el-button>
        <el-button
          style="margin-right: 20px"
          type="primary"
          size="small"
          icon="el-icon-refresh"
          @click="getList"
        >
          刷新
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="recommendVisible = true"
        >
          批量添加推荐商品
        </el-button>
      </template>
      <template
        slot="menu"
        slot-scope="scope"
      >
        <!-- <el-button
          type="text"
          size="small"
          icon="el-icon-delete"
          @click="view(scope.row, scope.index)"
        >
          查看
        </el-button> -->
        <el-button
          v-if="
            scope.row.status !== PET_STATE.ADOPTED &&
            scope.row.status !== PET_STATE.YIHUIMIAOXING
          "
          type="text"
          size="small"
          @click="edit(scope.row, scope.index)"
        >
          编辑
        </el-button>
        <el-button
          v-if="scope.row.status === PET_STATE.PENDING_SHELF"
          type="text"
          size="small"
          @click="putAway(scope.row, false)"
        >
          上架
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          @click="putAway(scope.row, true)"
        >
          更新上架
        </el-button>
        <!-- <el-button
          v-if="scope.row.status === PET_STATE.PENDING_ADOPTION"
          type="text"
          size="small"
          icon="el-icon-delete"
          @click="takeDown(scope.row, scope.index)"
        >
          下架
        </el-button> -->
        <el-button
          v-if="
            scope.row.status !== PET_STATE.ADOPTED &&
            scope.row.status !== PET_STATE.PENDING_GIVE &&
            scope.row.status !== PET_STATE.YIHUIMIAOXING &&
            scope.row.status !== PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="sign(scope.row, scope.index)"
        >
          领养签约
        </el-button>
        <el-button
          v-if="scope.row.status === PET_STATE.PENDING_GIVE"
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="giveSign(scope.row)"
        >
          送养签约
        </el-button>
        <el-button
          v-if="
            scope.row.status !== PET_STATE.ADOPTED &&
            scope.row.status !== PET_STATE.PENDING_GIVE &&
            scope.row.status !== PET_STATE.YIHUIMIAOXING
          "
          type="text"
          size="small"
          icon="el-icon-delete"
          @click="addTrace(scope.row, scope.index)"
        >
          溯源
        </el-button>
        <el-button
          v-if="
            (scope.row.status === PET_STATE.PENDING_SHELF ||
              scope.row.status === PET_STATE.PENDING_GIVE) &&
            [VIDEO_STATUS.IS_NULL, VIDEO_STATUS.TRANSCODING_FAILURE].includes(
              scope.row.videoStatus
            )
          "
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="handleDelete(scope.row, scope.index)"
        >
          删除
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.ADOPTED ||
            scope.row.status === PET_STATE.YIHUIMIAOXING ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          @click="comment(scope.row, scope.index)"
        >
          评论管理
        </el-button>
        <el-button
          v-if="
            [
              PET_STATE.ADOPTED,
              PET_STATE.PENDING_ADOPTION,
              PET_STATE.CLOUD_IS_ADOPT,
            ].includes(scope.row.status) &&
            scope.row.reportFlag === REPORT_FLAG.NORMAL
          "
          type="text"
          size="small"
          @click="shield(scope.row, scope.index)"
        >
          屏蔽
        </el-button>
        <el-button
          v-if="
            [
              PET_STATE.ADOPTED,
              PET_STATE.PENDING_ADOPTION,
              PET_STATE.CLOUD_IS_ADOPT,
            ].includes(scope.row.status) &&
            scope.row.reportFlag === REPORT_FLAG.BE_REPORTED
          "
          type="text"
          size="small"
          @click="recover(scope.row, scope.index)"
        >
          恢复
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.ADOPTED ||
            scope.row.status === PET_STATE.YIHUIMIAOXING
          "
          type="text"
          size="small"
          @click="updateStory(scope.row, scope.index)"
        >
          更新故事
        </el-button>
        <el-button
          v-if="
            scope.row.status !== PET_STATE.PENDING_GIVE ||
            scope.row.status === PET_STATE.YIHUIMIAOXING
          "
          type="text"
          size="small"
          @click="goToTimeline(scope.row, scope.index)"
        >
          时间轴
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.ADOPTED ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          @click="like(scope.row, scope.index)"
        >
          点赞
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.ADOPTED ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          @click="commentview(scope.row, scope.index)"
        >
          评论
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT ||
            scope.row.status === PET_STATE.PENDING_SHELF
          "
          type="text"
          size="small"
          @click="goCatStar(scope.row, scope.index)"
        >
          回归喵星
        </el-button>
        <el-button
          v-if="
            (scope.row.status === PET_STATE.PENDING_ADOPTION ||
              scope.row.status === PET_STATE.ADOPTED ||
              scope.row.status === PET_STATE.CLOUD_IS_ADOPT) &&
            scope.row.topFlag === TOPFLAG.NOTOP
          "
          type="text"
          size="small"
          @click="top(scope.row, TOPFLAG.TOP)"
        >
          置顶
        </el-button>
        <el-button
          v-if="
            (scope.row.status === PET_STATE.PENDING_ADOPTION ||
              scope.row.status === PET_STATE.ADOPTED ||
              scope.row.status === PET_STATE.CLOUD_IS_ADOPT) &&
            scope.row.topFlag === TOPFLAG.TOP
          "
          type="text"
          size="small"
          @click="top(scope.row, TOPFLAG.NOTOP)"
        >
          取消置顶
        </el-button>
        <el-button
          v-if="
            scope.row.status === PET_STATE.PENDING_ADOPTION ||
            scope.row.status === PET_STATE.ADOPTED ||
            scope.row.status === PET_STATE.CLOUD_IS_ADOPT
          "
          type="text"
          size="small"
          @click="recommandCommodity(scope.row)"
        >
          推荐商品
        </el-button>
      </template>
    </avue-crud>
    <addPopup
      v-model="addVisible"
      @success="(val) => getList(page, val)"
    ></addPopup>
    <editPopup
      :id="id"
      v-model="editVisible"
      @success="(val) => getList(page, val)"
    ></editPopup>
    <detailPopup
      :id="id"
      v-model="detailVisible"
      :status="theStatus"
    ></detailPopup>
    <tracePopup
      :id="id"
      v-model="traceVisible"
      @success="(val) => getList(page, val)"
    ></tracePopup>
    <signPopup
      :id="id"
      v-model="signVisible"
      @success="(val) => getList(page, val)"
    ></signPopup>
    <putAwayPopup
      :id="id"
      v-model="putAwayVisible"
      :is-update-shelf="isUpdateShelf"
      @success="(val) => getList(page, val)"
    ></putAwayPopup>
    <commentPopup
      :id="id"
      v-model="commentVisible"
      :pet-code="petCode"
    ></commentPopup>
    <timeLine
      :id="id"
      v-model="timeLineVisible"
    ></timeLine>
    <like-dialog
      :id="id"
      v-model="likeVisible"
      :action="action"
      :relative-type="CONTENT_TYPE.PET"
      @success="getList"
    ></like-dialog>
    <account-comment-dialog
      :id="id"
      v-model="accountVisible"
      :relative-type="CONTENT_TYPE.PET"
      @success="getList"
    ></account-comment-dialog>
    <update-story
      :id="id"
      v-model="storyVisible"
      @success="getList"
    ></update-story>
    <base-top-time-dialog
      :id="id"
      v-model="topVisible"
      @success="getList"
    ></base-top-time-dialog>
    <el-dialog
      title="推荐它喜欢的商品"
      :visible.sync="goodsVisible"
      width="60%"
      append-to-body
    >
      <like-goods
        v-if="goodsVisible"
        :id="id"
        ref="likeGoods"
        @success="submitSuccess"
        @loading="(val) => (loading = val)"
      ></like-goods>
      <div class="flex-end">
        <el-button
          class="btn"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          保存商品信息
        </el-button>
        <el-button @click="goodsVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <batch-recommend-popup v-model="recommendVisible"></batch-recommend-popup>
  </basic-container>
</template>

<script>
import {
  fetchBasePetList,
  delObj,
  takeDown,
  shieldPet,
  recoverPet,
  returnMeowStar,
  topPetBase,
} from '@/api/core/pet-file';
import { tableOption } from '@/const/crud/pet/base-file';
import { mapGetters } from 'vuex';
import crudMixins from '@/mixins/crud';
import detailPopup from './components/detailPopup.vue';
import tracePopup from './components/tracePopup.vue';
import addPopup from './components/addPopup.vue';
import editPopup from './components/editPopup.vue';
import signPopup from './components/signPopup.vue';
import putAwayPopup from './components/putAwayPopup.vue';
import commentPopup from './components/commentPopup.vue';
import timeLine from './components/timeLine.vue';
import { remote } from '@/api/admin/dict';
import { getTree } from '@/api/core/classify';
import {
  PET_STATE,
  REPORT_FLAG,
  VIDEO_STATUS,
  CONTENT_TYPE,
  TOPFLAG,
} from '@/const/type';
import likeDialog from '../../community-content/component/likeDialog.vue';
import accountCommentDialog from '../../community-content/component/accountCommentDialog.vue';
import UpdateStory from './components/updateStory.vue';
import baseTopTimeDialog from './components/baseTopTimeDialog.vue';
import BatchRecommendPopup from './components/batchRecommendPopup.vue';
import likeGoods from './components/likeGoods.vue';
export default {
  name: 'manage',
  components: {
    BatchRecommendPopup,
    detailPopup,
    tracePopup,
    addPopup,
    signPopup,
    putAwayPopup,
    editPopup,
    commentPopup,
    timeLine,
    likeDialog,
    accountCommentDialog,
    UpdateStory,
    baseTopTimeDialog,
    likeGoods,
  },
  mixins: [crudMixins],
  data() {
    return {
      props: { multiple: true },
      recommendVisible: false,
      addVisible: false,
      storyVisible: false,
      likeVisible: false,
      accountVisible: false,
      editVisible: false,
      detailVisible: false,
      traceVisible: false,
      signVisible: false,
      putAwayVisible: false,
      goodsVisible: false,
      form: {},
      tableOption: tableOption(),
      id: null,
      loading: false,
      action: '',
      commentVisible: false,
      topVisible: false,
      PET_STATE,
      CONTENT_TYPE,
      petCode: '',
      REPORT_FLAG,
      isUpdateShelf: false,
      VIDEO_STATUS,
      TOPFLAG,
      timeLineVisible: false,
      theStatus: '',
      petMatters: [],
      options: [],
      treeData: [],
    };
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  watch: {
    role() {
      this.form.role = this.role;
    },
  },
  created() {
    this.getPetMatters();
    this.getTree();
  },
  methods: {
    async submitSuccess() {
      this.goodsVisible = false;
      this.$message.success('操作成功！');
      this.getList();
    },
    submit() {
      this.$refs.likeGoods.submit([this.id]);
    },
    //推荐商品
    recommandCommodity(row) {
      console.log('rrr', row);
      console.log('进来了麻');
      this.goodsVisible = true;
      this.id = row.id;
    },
    searchReset() {
      this.searchForm = {};
      this.$refs.crud.$refs.headerSearch.searchForm.petType = [];
      this.getList();
    },
    getTree() {
      getTree().then((res) => {
        this.options = res.data.data;
      });
    },
    getPetMatters() {
      remote('pet_matters').then((res) => {
        this.petMatters = res.data.data;
        this.petMatters.shift();
      });
    },
    giveSign() {
      this.$router.push({
        path: '/pet/contractMng/index',
        query: {
          isOpen: true,
        },
      });
    },
    comment(row) {
      this.id = row.id;
      this.petCode = row.code;
      this.commentVisible = true;
    },
    add() {
      this.id = null;
      this.addVisible = true;
    },
    goToTimeline(row) {
      this.id = row.id;
      this.timeLineVisible = true;
    },
    view(row) {
      this.id = row.id;
      this.theStatus = row.status;
      this.detailVisible = true;
    },
    edit(row) {
      this.id = row.id;
      this.editVisible = true;
    },
    addTrace(row) {
      this.id = row.id;
      this.traceVisible = true;
    },
    sign(row) {
      this.id = row.id;
      this.signVisible = true;
    },
    //点赞
    like(row) {
      this.likeVisible = true;
      this.action = 'like';
      this.id = row.id;
    },
    //评论
    commentview(row) {
      this.accountVisible = true;
      this.id = row.id;
    },
    //回归喵星
    goCatStar(row) {
      const tips =
        row.status === PET_STATE.PENDING_SHELF
          ? '您确认喵喵已回归喵星了吗？操作后将无法恢复原有状态，请谨慎操作哦!'
          : '您确认喵喵已回归喵星了吗？操作后将无法恢复原有状态，且APP和小程序端将不再展示此猫咪上架信息，请谨慎操作哦！';
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const params = {
          id: row.id,
        };
        await returnMeowStar(params);
        this.$message.success('回归喵星成功');
        this.getList(this.page, true);
      });
    },
    //置顶 取消置顶
    top(row, status) {
      this.id = row.id;
      if (status === TOPFLAG.NOTOP) {
        const tip =
          '取消置顶后，该内容会恢复默认排序，不再靠前展示，确定取消置顶吗？';
        this.$confirm(`${tip}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(function () {
            const params = {
              id: row.id,
              flag: status,
            };
            return topPetBase(params);
          })
          .then(() => {
            this.getList();
          });
      } else {
        this.topVisible = true;
      }
    },
    // 更新故
    updateStory(row) {
      this.id = row.id;
      this.storyVisible = true;
    },
    putAway(row, flag) {
      if (row.videoStatus === VIDEO_STATUS.TRANSCODING) {
        this.$message.warning(
          '你上传的视频正在转码中，请在转码成功后再进行更新上架！'
        );
        return;
      } else {
        this.id = row.id;
        this.putAwayVisible = true;
        this.isUpdateShelf = flag;
      }
    },
    shield(row) {
      this.$confirm(
        '【屏蔽后该宠物在移动用户端将不可见，是否确定屏蔽该宠物？】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        await shieldPet(row.id);
        this.$message.success('屏蔽成功');
        this.getList(this.page, true);
      });
    },
    recover(row) {
      this.$confirm(
        '【恢复后该宠物在移动用户端将可见，是否确定恢复该宠物？】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        await recoverPet(row.id);
        this.$message.success('恢复成功');
        this.getList(this.page, true);
      });
    },
    takeDown(row) {
      this.id = row.id;
      this.$confirm('是否确认下架该条宠物档案?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await takeDown({ id: this.id });
        })
        .then(() => {
          this.getList(this.page, true);
          this.$message.success('下架成功');
        });
    },
    handleDelete(row) {
      this.$confirm('是否确认删除该条宠物档案?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return delObj(row.id);
        })
        .then(() => {
          this.getList(this.page, true);
          this.$message.success('删除成功');
        });
    },
    // 列表查询
    getList(page, refresh) {
      const catList = [];
      const dogList = [];
      this.searchForm.typeCodeList = [];
      this.searchForm.varietyCodeList = [];
      //品种的搜索条件
      if (!this.validatenull(this.searchForm.petType)) {
        this.searchForm.petType.forEach((item) => {
          if (item[0] === 'CAT') {
            catList.push(item[1]);
          } else if (item[0] === 'DOG') {
            dogList.push(item[1]);
          }
        });
        if (catList.length > 0) {
          this.searchForm.typeCodeList.push('CAT');
        }
        if (dogList.length > 0) {
          this.searchForm.typeCodeList.push('DOG');
        }
        this.searchForm.varietyCodeList = catList.concat(dogList);
      }
      if (refresh) {
        this.page.current = 1;
        this.page.currentPage = 1;
      }
      this.tableLoading = true;
      const timeObj = {};
      if (this.searchForm.receiveDate && this.searchForm.receiveDate.length) {
        timeObj.receiveDateStart = this.searchForm.receiveDate[0];
        timeObj.receiveDateEnd = this.searchForm.receiveDate[1];
        // delete this.searchForm.receiveDate;
      }
      if (this.searchForm.shelfTime && this.searchForm.shelfTime.length) {
        timeObj.shelfTimeStart = this.searchForm.shelfTime[0];
        timeObj.shelfTimeEnd = this.searchForm.shelfTime[1];
      }
      let statusLists = [];

      if (this.searchForm.status) {
        if (Array.isArray(this.searchForm.status)) {
          statusLists = this.searchForm.status;
        } else {
          statusLists = this.searchForm.status.split(',');
        }
      }
      fetchBasePetList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize,
            statusList: statusLists || [],
            matterValueList: this.searchForm.matterValue,
          },

          this.searchForm,
          timeObj
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.tableData.forEach((el) => {
            el.videoStatus = el.videoStatus || 'notExist';
            el.petType = [el.typeName, el.varietyName];
            // el.varietyCodeList = [el.varietyCodeList];
            // el.typeCode = [el.typeCode];
            // el.avatar = JSON.parse(el.avatar)[0].url;
            // el.avatar =
            //   'https://img.alicdn.com/tfs/TB1v28TC8v0gK0jSZKbXXbK2FXa-1880-640.jpg';
          });
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
